<?php

namespace App\Models\V1;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model as BaseModel;

/**
 * @method create(array $attributes)
 */
class Model extends BaseModel
{
    protected $dateFormat = 'U';


    /**
     * ID排序
     *
     * @param Builder $query
     * @return Builder
     */
    public function scopeRecent(Builder $query): Builder
    {
        return $query->orderByDesc('id');
    }

    /**
     * ID排序
     *
     * @param Builder $query
     * @param string $relation
     * @param array $columns
     * @param bool $isAddForeignKey
     * @return Builder
     */
    public function scopeWithSelect(Builder $query, string $relation, array $columns = ['*']): Builder
    {
        // 主键必须存在才能生效
        if ($columns[0] != '*') {
            if (!in_array($this->primaryKey, $columns)) {
                $columns[] = $this->primaryKey;
            }
        }

        return $query->with([$relation => function ($query) use ($columns) {
            $query->select($columns);
        }]);
    }
}
